/*
 * Copyright © 2011 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.classes;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.Sprite;
import java.util.*;

/**
 *
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class CartoonClockCanvas extends Canvas {

	private static final String imgPath = "/numbers.png";

	private int widthOfNumber = 0;
	private int heightOfNumber = 0;
	private Image image = null;
	private Timer timer = null;
	private RefreshTimerTask timerTask = null;
	
	private Calendar calendar = null;
	private int hour = 0;
	private int minute = 0;
	private int second = 0;
	private int part1OfNumber = 0;
	private int part2OfNumber = 0;
	
	public CartoonClockCanvas() {
		try {
			image = Image.createImage(imgPath);
		} catch(Exception ex) {
			ex.printStackTrace();
			return;
		}
		widthOfNumber = image.getWidth() / 11;
		heightOfNumber = image.getHeight();
	
		timer = new Timer();
		timerTask = new RefreshTimerTask();
		timer.schedule(timerTask, 0, 150);
	}
	
	public void paint(Graphics g) {
		g.setColor(255, 255, 255);
		g.fillRect(0, 0, getWidth(), getHeight());
		part1OfNumber = hour/10;
		part2OfNumber = hour%10;
		drawNumber(g, part1OfNumber, 0);
		drawNumber(g, part2OfNumber, 1);
		drawNumber(g, 10, 2);
		part1OfNumber = minute/10;
		part2OfNumber = minute%10;
		drawNumber(g, part1OfNumber, 3);
		drawNumber(g, part2OfNumber, 4);
		drawNumber(g, 10, 5);
		part1OfNumber = second/10;
		part2OfNumber = second%10;
		drawNumber(g, part1OfNumber, 6);
		drawNumber(g, part2OfNumber, 7);
	}
	
	//根据number从图片中取一个数字，画在画布的location位置
	private void drawNumber(Graphics g, int number, int location) {		//冒号用数字10代替
		int x_src = number * widthOfNumber;
		int y_src = 0;
		int width = widthOfNumber;
		int height = heightOfNumber;
		int x_dest = location * widthOfNumber;
		int y_dest = 10;
		g.drawRegion(image, x_src, y_src, width, height, Sprite.TRANS_NONE, x_dest, y_dest, Graphics.LEFT|Graphics.TOP);
	}
	
	class RefreshTimerTask extends TimerTask {
		public void run() {
			calendar = Calendar.getInstance();
			hour = calendar.get(Calendar.HOUR_OF_DAY);
			minute = calendar.get(Calendar.MINUTE);
			second = calendar.get(Calendar.SECOND);
			repaint();
		}
	}
	
}
